package com.cd.servlet;

import cn.hutool.Hutool;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cd.dao.StudentDAO;
import com.cd.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private StudentDAO studentDAO;
	@Override
	public void init() throws ServletException {
		studentDAO = new StudentDAO();
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			// 指定响应json类型（网页+utf8字符集编码）
			resp.setContentType("application/json;charset=utf-8");
			req.setCharacterEncoding("utf-8");
			List<Student> students = studentDAO.findAll();
			String jsonStr = JSONUtil.toJsonStr(students);
			resp.getWriter().write(jsonStr);
			resp.getWriter().close();

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
